package com.fenghongzhang.kotlin5.day05

import android.content.Context
import android.content.SharedPreferences
import com.fenghongzhang.kotlin5.App
import com.fenghongzhang.kotlin5.MainActivity
import java.lang.IllegalArgumentException
import kotlin.reflect.KProperty

//代理类-> 委托类
class MySP<T>(val key:String, val value:T){

    //懒加载
    private val sp:SharedPreferences by lazy {
        App.context.getSharedPreferences("user",Context.MODE_PRIVATE)
    }

    //第一个参数,代表可以用到哪个类中
    //当前类属性的操作
    operator fun getValue(clzss:Any?,pro:KProperty<*>) = getSP(key,value)

    private fun getSP(key: String, value: T) : T = with(sp){
        var v = when(value){
            is String -> getString(key,value)
            is Boolean -> getBoolean(key,value)
            is Int -> getInt(key,value)
            is Float -> getFloat(key,value)
            is Long -> getLong(key,value)
            else -> IllegalArgumentException("参数错了")
        }
        return v as T
    }

    //第一个参数,代表可以用到哪个类中
    //当前类属性的操作
    //第三个就是赋值的参数
    operator fun setValue(clzss:Any?,pro:KProperty<*>,vaule: T){
        setSP(key,vaule)
    }

    //with方法, when方法
   fun setSP(key: String,v: T) = with(sp.edit()){
       when(v){
           is Int -> putInt(key,v)
           is Float -> putFloat(key,v)
           is Long -> putLong(key,v)
           is Boolean -> putBoolean(key,v)
           is String -> putString(key,v)
           else -> throw IllegalArgumentException("错误了")
       }.apply()
   }

}

//代理类
object SPUitl{
    //泛型方法
    fun <T> opertion(key: String,value:T) = MySP(key,value)
}